import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { NetworkConfig } from '../../app/app.service'

import 'rxjs/add/operator/toPromise';

@Injectable()
export class DfHTTP {
    domain: string = NetworkConfig.domain;
    constructor(private http: Http) { }

    fullGet(url, params?): Promise<any> {
        url += '?';
        for (let key in params) {
            url += `${key}=${params[key]}&`;
        }
        return this.http.get(url)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    fullPost(url, params?): Promise<any> {
        return this.http.post(url, params, { headers: NetworkConfig.headers })
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    get(url, params?): Promise<any> {
        var fullURL = this.domain + url;
        return this.fullGet(fullURL, params);
    }
    post(url, params?): Promise<any> {
        var fullURL = this.domain + url;
        return this.fullPost(fullURL, params);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

